package main

import (
	"bufio"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	// 要遍历的路径列表（你可以根据需要修改）
	paths := []string{
		"../../pkg",
		"../../tests",
		"../basic_add/main.go", // 也支持直接指定 .go 文件
	}

	outputFile := "./output.md"
	out, err := os.Create(outputFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "无法创建输出文件 %s: %v\n", outputFile, err)
		os.Exit(1)
	}
	defer out.Close()

	writer := bufio.NewWriter(out)
	defer writer.Flush()

	for _, path := range paths {
		err := processPath(path, writer)
		if err != nil {
			fmt.Fprintf(os.Stderr, "处理路径 %s 时出错: %v\n", path, err)
		}
	}

	fmt.Printf("所有 .go 文件已写入 %s\n", outputFile)
}

// processPath 处理单个路径：如果是目录则递归，如果是 .go 文件则处理
func processPath(path string, writer *bufio.Writer) error {
	info, err := os.Stat(path)
	if err != nil {
		return fmt.Errorf("无法访问路径 %s: %w", path, err)
	}

	if info.IsDir() {
		return filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error {
			if err != nil {
				return err
			}
			if !d.IsDir() && strings.HasSuffix(path, ".go") {
				return writeGoFileToMD(writer, path)
			}
			return nil
		})
	} else if strings.HasSuffix(path, ".go") {
		return writeGoFileToMD(writer, path)
	}
	// 忽略非 .go 文件和非目录
	return nil
}

// writeGoFileToMD 将单个 .go 文件内容写入 Markdown
func writeGoFileToMD(writer *bufio.Writer, filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("无法打开文件 %s: %w", filePath, err)
	}
	defer file.Close()

	// 写入标题
	fmt.Fprintf(writer, "## `%s`\n\n", filePath)

	// 写入代码块开始
	writer.WriteString("```go\n")

	// 逐行复制内容
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		writer.WriteString(scanner.Text() + "\n")
	}
	if err := scanner.Err(); err != nil {
		return fmt.Errorf("读取文件 %s 时出错: %w", filePath, err)
	}

	// 结束代码块
	writer.WriteString("```\n\n")

	return nil
}
